package com.tch.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

@Component
@Slf4j
public class HttpUtils {

    public static String sendPostFile(String urlString, File file) {
        String result = null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpResponse response = null;
        try {
            if (file.exists()) {
                HttpPost httpPost = new HttpPost(urlString);
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
                FileBody fileBody = new FileBody(file);//把文件转换成流对象FileBody
                builder.addPart("file", fileBody);

                HttpEntity entity = builder.build();// 生成 HTTP POST 实体
                httpPost.setEntity(entity);
                response = client.execute(httpPost);
                result = StreamUtils.copyToString(response.getEntity().getContent(), Charset.forName("UTF-8"));
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
        }
        return result;
    }


    public static String sendPost(String urlString, java.io.File file) {
        log.info("");
        String result = "";
        try {
            if (file.exists()) {
                HttpClient client = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(urlString);
                MultipartEntity entity = new MultipartEntity();
                entity.addPart("file", new FileBody(file));

                httpPost.setEntity(entity);
                HttpResponse response = client.execute(httpPost);

                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity);
                System.out.println(result);
            }
        } catch (Exception e) {
            log.error("发送POST请求出现异常！", e);
        }
        return result.toString();
    }

    public static String accessPlatformService(String urlStr, String requestJson) {

        HttpURLConnection httpURLConnection = null;
        BufferedReader bf = null;
        DataOutputStream dataOut = null;
        String returnStr = "";
        try {
            // 创建url
            URL url = new URL(urlStr);

            // 创建http链接
            httpURLConnection = (HttpURLConnection) url.openConnection();

            // 设置请求的方法类型
            httpURLConnection.setRequestMethod("POST");

            // 设置请求的内容类型
            httpURLConnection.setRequestProperty("Content-type", "application/json");
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置发送数据
            httpURLConnection.setDoOutput(true);

            // 设置接受数据
            httpURLConnection.setDoInput(true);

            // 设置该HttpURLConnection实例是否自动执行重定向
            httpURLConnection.setInstanceFollowRedirects(true);

            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            httpURLConnection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数
            //dataOut = new DataOutputStream(httpURLConnection.getOutputStream());
            httpURLConnection.getOutputStream().write(requestJson.getBytes());

            //// 发送数据
            //dataOut.writeBytes(requestJson);

            // 连接发起请求，处理服务器响应
            bf = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = bf.readLine()) != null) {
                sb.append(line);
            }
            returnStr = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (dataOut != null) {
                    dataOut.flush();
                    dataOut.close();
                }
                if (bf != null) {
                    bf.close();
                }
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect(); // 销毁连接
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return returnStr;
    }


    /**
     * 发送get请求
     * @param url 请求URL
     * @param param 请求参数 key:value url携带参数 或者无参可不填
     * @return
     */
    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


}
